package Server;

import java.util.Date;

public class Call {

	public enum State {
		RINGING,
		IN_CALL,
		END_CALL,
		OFF_CALL
	}
	
	private PhoneServerThread caller;
	private PhoneServerThread callee;
	
	private State call_state;
	
	private Date ring_time;
	private Date start_time;
	private Date end_time;
	
	private double rate;
	
	public Call(PhoneServerThread caller, PhoneServerThread callee) {
		this.caller = caller;
		this.callee = callee;
		call_state = State.RINGING;
		ring_time = new Date();
	}
	
	public void CleanUp() {
		if(call_state == State.IN_CALL) {
			end_time = new Date();
			PhoneServerDB.getPhoneServerDB().insertCallRecord(start_time, end_time, rate, caller.getExtension(), callee.getExtension());
			
			start_time = new Date();
			rate = PhoneServerDB.getPhoneServerDB().getDiscountRate(caller.getExtension(), start_time);
			
		} else if (call_state == State.END_CALL){		
			PhoneServerDB.getPhoneServerDB().insertCallRecord(start_time, end_time, rate, caller.getExtension(), callee.getExtension());
		}
	}
	
	public void startCall() {
		call_state = State.IN_CALL;		
		start_time = new Date();
		rate = PhoneServerDB.getPhoneServerDB().getDiscountRate(caller.getExtension(), start_time);
	}
	
	public void endCall() {
		call_state = State.END_CALL;		
		end_time = new Date();
	}
	
	public State getState() {
		return call_state;
	}
	
	public Date getStartTime() {
		return start_time;
	}
	
	public Date getEndTime() {
		return end_time;
	}
	
	public double getRate() {
		return rate;
	}
	
	public boolean ringTimeout() {
		long curr = System.currentTimeMillis();
		return ((curr - ring_time.getTime()) >= 22000);
	}
	
	public PhoneServerThread getCaller() {
		return caller;
	}
	
	public PhoneServerThread getCallee() {
		return callee;
	}
}
